<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    :title="t('mail.mailInfo')"
    custom-class="dialog-min-width"
    width="500"
    :destroy-on-close="true"
  >
    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formEdit"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-alert
            :title="t('mail.mailTip')"
            type="warning"
            :closable="false"
          /><br />
        </el-col>
      </el-row>
      <el-row>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('mail.host')" prop="host">
            <el-input v-model="formEdit.host" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('mail.port')" prop="port">
            <el-input-number
              v-model="formEdit.port"
              :min="25"
              :max="1024"
              :controls="false"
              class="fix-el-input-number-width fix-el-input-number-align"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('mail.from')" prop="from">
            <el-input v-model="formEdit.from" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('mail.user')" prop="user">
            <el-input v-model="formEdit.user" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item :label="t('mail.password')" prop="password">
            <el-input v-model="formEdit.password" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import utils from "../../../utils/utils";
import apiMail from "../api/mail";
import apiAccount from "../api/account";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const formRef = ref();
const loading = ref(false);

const publicKey = ref("");

const formEditOriginal = () => {
  return {
    sessionId: "",
    host: "",
    port: "",
    from: "",
    user: "",
    password: "",
  };
};
const formEdit = reactive(formEditOriginal());

const rules = reactive({
  host: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  port: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  from: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  user: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
});

const state = reactive({
  dialogFormVisible: false,
});

const emit = defineEmits<{
  (event: "on-submit-success"): void;
}>();

const handleSubmit = async () => {
  await formRef.value.validate();

  // 加密数据，清理原文
  let encryptedFrom = utils.doSm2Encrypt(publicKey.value, formEdit.from);
  let encryptedUser = utils.doSm2Encrypt(publicKey.value, formEdit.user);
  let encryptedPassword = utils.doSm2Encrypt(
    publicKey.value,
    formEdit.password
  );

  loading.value = true;
  apiMail
    .configMail(
      formEdit.sessionId,
      formEdit.host,
      formEdit.port,
      encryptedFrom,
      encryptedUser,
      encryptedPassword
    )
    .then((response: any) => {
      loading.value = false;
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success");
      }
    })
    .catch((err: any) => {
      loading.value = false;
      utils.errorNotification(t("common.submitException"), err);
    });
};

const getPublicKey = () => {
  formEdit.sessionId = utils.getUUID();
  apiAccount
    .generateSessionPublicKeyQ(formEdit.sessionId)
    .then((response: any) => {
      if (response.data.code == 200) {
        publicKey.value = response.data.data;
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = () => {
  // console.log(row);
  Object.assign(formEdit, formEditOriginal());
  apiMail
    .getMailConfig()
    .then((response: any) => {
      if (response.data.code == 200) {
        Object.assign(formEdit, response.data.data);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
  getPublicKey();
  loading.value = false;
  state.dialogFormVisible = true;
};

defineExpose({
  show,
});
</script>
